package me.chan.chatting.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.chatting.server.factory.SessionServiceFactory;
import me.chan.chatting.server.msg.ChatRequestMessage;
import me.chan.chatting.server.msg.ChatResponseMessage;

import java.util.Objects;

@ChannelHandler.Sharable
@Slf4j
public class ChatInboundHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {

        String fromUser = msg.getFrom();
        String toUser = msg.getTo();
        String content = msg.getContent();
        log.debug("receive message from {}:{}", fromUser, content);
        Channel channel = SessionServiceFactory.getInstance().getChannel(toUser);
        if (Objects.isNull(channel)) {
            ctx.writeAndFlush(new ChatResponseMessage(false,"could not send to " + toUser + " cause he/she is offline"));
            return ;
        }

        ChatResponseMessage responseMessage = new ChatResponseMessage(fromUser, content);
        channel.writeAndFlush(responseMessage);


    }
}
